package com.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.order.entity.ResOrderStage;
import com.order.entity.ResOrderStageTemplate;
import com.order.entity.ResOrderType;
import com.order.service.ResOrderStageService;
import com.order.service.ResOrderStageTemplateService;
import com.order.service.ResOrderTypeService;
import com.bhudy.base.BaseServiceImpl;
import com.order.entity.ResOrder;
import com.order.service.ResOrderService;
import com.bhudy.base.QueryFilter;
import com.sys.utils.ShiroUtils;
import com.sys.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
 * @Author 卞洪业
 * @Description ResOrderServiceImpl
 * @Date Wed Feb 19 17:04:47 CST 2020
 */
@Service
public class ResOrderServiceImpl extends BaseServiceImpl<ResOrder, Serializable> implements ResOrderService {

    @Autowired
    private ResOrderStageService resOrderStageService;
    @Autowired
    private ResOrderTypeService resOrderTypeService;
    @Autowired
    private ResOrderStageTemplateService resOrderStageTemplateService;

    @Override
    public Map<String, Object> getResOrderById(Long resOrderId) {
        ResOrder resOrder = super.get(resOrderId);
        if (resOrder == null) throw new SysException(SysExceptionCode.CODE_40002);

        List<ResOrder> resOrderList = new ArrayList<>();
        resOrderList.add(resOrder);

        return this.getResOrderMapList(resOrderList).get(0);
    }

    public List<Map<String, Object>> getResOrderMapList(List<ResOrder> resOrderList) {
        List<Map<String, Object>> resOrderMapList = new ArrayList<>();
        QueryFilter queryFilter = new QueryFilter();
        if (Utils.isBlank(resOrderList)) {
            List<ResOrderType> resOrderTypeList = resOrderTypeService.findList(queryFilter.clear());
            Map<Long, ResOrderType> idAndResOrderTypeMapping = new HashMap<>();
            for (ResOrderType resOrderType : resOrderTypeList) {
                idAndResOrderTypeMapping.put(resOrderType.getResOrderTypeId(), resOrderType);
            }

            List<ResOrderStage> resOrderStageList = resOrderStageService.findList(queryFilter.clear().orderASC("sort"));
            Map<Long, List<ResOrderStage>> resOrderStageMapping = new HashMap<>();
            if (Utils.isBlank(resOrderStageList)) {
                for (ResOrderStage resOrderStage : resOrderStageList) {
                    Long key = resOrderStage.getResOrderId();
                    if (resOrderStageMapping.containsKey(key)) {
                        resOrderStageMapping.get(key).add(resOrderStage);
                    } else {
                        List<ResOrderStage> orderStageList = new ArrayList<>();
                        orderStageList.add(resOrderStage);
                        resOrderStageMapping.put(key, orderStageList);
                    }
                }
            }
            List<ResOrderStageTemplate> resOrderStageTemplateList = resOrderStageTemplateService.findList(queryFilter.clear().orderASC("stageSort"));
            Map<Long, List<ResOrderStageTemplate>> resOrderStageTemplateMapping = new HashMap<>();
            Map<String, String> resOrderStageTemplateIdAndNameMapping = new HashMap<>();
            if (Utils.isBlank(resOrderStageTemplateList)) {
                for (ResOrderStageTemplate resOrderStageTemplate : resOrderStageTemplateList) {
                    Long key = resOrderStageTemplate.getResOrderTypeId();
                    resOrderStageTemplateIdAndNameMapping.put(key + "_" + resOrderStageTemplate.getStageSort(), resOrderStageTemplate.getTemplateName());

                    if (resOrderStageTemplateMapping.containsKey(key)) {
                        resOrderStageTemplateMapping.get(key).add(resOrderStageTemplate);
                    } else {
                        List<ResOrderStageTemplate> orderStageTemplateList = new ArrayList<>();
                        orderStageTemplateList.add(resOrderStageTemplate);
                        resOrderStageTemplateMapping.put(key, orderStageTemplateList);
                    }
                }
            }

            for (ResOrder resOrder : resOrderList) {
                Map<String, Object> resOrderMap = JSONObject.parseObject(JSONObject.toJSONString(resOrder), Map.class);
                ResOrderType resOrderType = idAndResOrderTypeMapping.get(resOrder.getResOrderTypeId());
                resOrderMap.put("isOperation", resOrder.getUserId().equals(ShiroUtils.getUserId())); // 是否能操作
                resOrderMap.put("templateName", resOrderStageTemplateIdAndNameMapping.get(resOrder.getResOrderTypeId() + "_" + resOrder.getStageSort()));
                resOrderMap.put("resOrderStageList", resOrderStageMapping.get(resOrder.getResOrderId()));
                resOrderMap.put("resOrderStageTemplateList", resOrderStageTemplateMapping.get(resOrder.getResOrderTypeId()));
                resOrderMap.put("resOrderTypeName", resOrderType.getTypeName());
                resOrderMap.put("resOrderType", resOrderType);
                resOrderMap.put("orderButtonList", ResOrder.getOrderButton(resOrder.getStage(), resOrder.getOrderStatus()));
                resOrderMap.put("orderStatusMap", ResOrder.getOrderStatusMap(resOrder.getStage(), resOrder.getOrderStatus()));

                Integer kpi = null;
                if (Utils.isBlank(resOrderStageTemplateList)) {
                    for (ResOrderStageTemplate resOrderStageTemplate : resOrderStageTemplateList) {
                        if (resOrderStageTemplate.getStageSort().equals(resOrder.getStageSort())) {
                            kpi = resOrderStageTemplate.getKpi();
                            break;
                        }
                    }
                }

                long startDate = 0L;
                long endDate = 0L;
                if (Utils.isBlank(resOrderStageList)) {
                    int max = 0;
                    for (ResOrderStage resOrderStage : resOrderStageList) {
                        if (resOrderStage.getSort().equals(1)) {
                            startDate = resOrderStage.getCreateDate().getTime();
                        }
                        if (max < resOrderStage.getSort()) {
                            endDate = resOrderStage.getCreateDate().getTime();
                            max = resOrderStage.getSort();
                        }
                    }
                }

                Long newDate = new Date().getTime();
                Map<String, Long> useTime = new HashMap<>();
                useTime.put("total", resOrder.getStage() == 5 ? (endDate - startDate) : (newDate - startDate)); // 总使用时间`
                useTime.put("totalWeekend", resOrder.getStage() == 5 ? Utils.timeQuantum(startDate, endDate) : Utils.timeQuantum(startDate, newDate)); // 包含周末毫秒数
                Long activityTime = (kpi == null || kpi == 0 ? null : kpi - (newDate - endDate));
                useTime.put("activityTime", activityTime); // 活动时间
                resOrderMap.put("useTime", useTime);


                resOrderMapList.add(resOrderMap);
            }
        }
        return resOrderMapList;
    }

    /**
     * 获取下阶段处理人
     *
     * @param resOrder
     * @param resOrderStageList
     * @param resOrderStageTemplateList
     * @return
     */
    private Long getNextUserId(ResOrder resOrder, List<ResOrderStage> resOrderStageList, List<ResOrderStageTemplate> resOrderStageTemplateList) {
        Long userId = null;

        ResOrderStageTemplate template = null;
        if (Utils.isBlank(resOrderStageTemplateList)) {
            for (ResOrderStageTemplate resOrderStageTemplate : resOrderStageTemplateList) {
                if ((resOrder.getStageSort() + 1) == resOrderStageTemplate.getStageSort()) {
                    template = resOrderStageTemplate;
                }
            }
        }

        if (resOrder.getStageSort().equals(1)) {
            userId = resOrder.getUserId();
        } else if (resOrder.getStage().equals(ResOrder.Stage.FINISH.code) || (template != null && template.getStage().equals(ResOrder.Stage.FINISH.code))) {
            if (Utils.isBlank(resOrderStageList)) {
                for (ResOrderStage resOrderStage : resOrderStageList) {
                    if (resOrderStage.getSort().equals(1)) {
                        userId = resOrderStage.getUserId();
                    }
                }
            }
        } else {
            // 下一阶段
            userId = template.getUserId();
        }

        return userId;
    }
}
